import { JwtService } from '@midwayjs/jwt';
import { Provide, Inject, Config } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { UserDto, UserLoginDto } from '../dto/userDto';
import * as bcrypt from 'bcryptjs';
import { authDao } from '../dao/auth.dao';
import { UserService } from './user.service';
import { RedisService } from '@midwayjs/redis';

@Provide()
export class authService {
  @Inject()
  jwtService: JwtService;
  @Inject()
  ctx: Context;
  @Config('jwtConfig')
  jwtConfig;
  @Inject()
  authDao: authDao;
  @Inject()
  userService: UserService;
  @Inject()
  redis: RedisService;

  //注册接口
  async register(
    account: UserDto['account'],
    password: UserDto['password'],
    name: UserDto['name'],
    email: UserDto['email']
  ): Promise<object> {
    //校验account
    const userAccount = await this.userService.getUserByAccount(account);
    if (userAccount) {
      throw new Error('Account already exists');
    }

    //密码加密
    const hashPassword = await bcrypt.hash(password, 10);
    password = hashPassword;
    return await this.authDao.register(account, password, name, email);
  }
  //登录接口
  async login(
    account: UserLoginDto['account'],
    password: UserLoginDto['password']
  ) {
    //用account登录
    const user = await this.userService.getUserByAccount(account);

    if (!user) {
      throw new Error('用户不存在');
    }

    //验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);

    if (!isPasswordValid) {
      throw new Error('密码错误');
    }

    //发放令牌
    const token = await this.jwtService.sign(
      { user_id: user.user_id, validflag: user.valid_flag },
      this.jwtConfig.secret,
      {
        expiresIn: this.jwtConfig.expiresIn,
      }
    );

    //存储token在redis里面
    try {
        await this.redis.set(`user:${user.user_id}`, token);
    } catch (error) {
      console.log(error);
    }
    return  token ;
  }
}
